/**
 * Loadable
 *
 * 惰性加载包装
 */

import React, { FunctionComponent } from 'react';
import Loadable, { Options } from 'react-loadable';
import { Button, Spin, Icon } from 'antd';
import styles from './index.scss';

interface LoadingProps {
  error?: Error;
  timedOut?: boolean;
  pastDelay?: boolean;
  retry?: () => void;
}

const Loading: FunctionComponent<LoadingProps> = React.memo(({ error, timedOut, pastDelay, retry }) => {
  if (error)
    return (
      <div className={styles.root}>
        <p>加载失败，请重试!!!</p>
        <Button className={styles.retryBtn} type="primary" onClick={retry}>
          retry load
        </Button>
      </div>
    );
  else if (timedOut)
    return (
      <div className={styles.root}>
        <p>加载超时，请重试!!! </p>
        <Button className={styles.retryBtn} type="primary" onClick={retry}>
          retry load
        </Button>
      </div>
    );
  else if (pastDelay)
    return (
      <div className={styles.root}>
        <div>
          <Spin
            delay={100}
            size="large"
            spinning={true}
            className={styles.root}
            indicator={<Icon type="loading" className={styles.loadingIcon} />}
          />
        </div>
      </div>
    );
  else return null;
});

export const loadableWrap = (props: Partial<Options<any, any>>) =>
  Loadable({
    loading: Loading,
    delay: 200,
    timeout: 10000,
    ...props
  } as Options<any, any>);
